package movee.utils.network;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 *
 *
 * @author movee
 */
@Slf4j
public final class LocalHostUtils {

    private LocalHostUtils() { }

    public static InetAddress getLocalAddress() {
        InetAddress localAddr = null;
        try {
            List<InetAddress> candidates = new ArrayList<>();

            // 获取所有的网卡
            Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
            while (nics.hasMoreElements()) {
                NetworkInterface iface = nics.nextElement();
                // 遍历网卡上的所有ip地址
                Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
                while (inetAddrs.hasMoreElements()) {
                    InetAddress inetAddr = inetAddrs.nextElement();
                    // 排除loopback回环类型地址（不管是IPv4还是IPv6）
                    if (inetAddr.isSiteLocalAddress()) {
                        candidates.add(inetAddr);
                    }
                }
            }

            InetAddress hostAddress = InetAddress.getLocalHost();
            localAddr = candidates.stream().filter(addr -> addr.getHostAddress().startsWith("10."))
                    .findFirst().orElse(candidates.stream().findFirst().orElse(hostAddress));
        } catch (Exception e) {
            log.warn("get site local address failed");
        }

        if (Objects.isNull(localAddr)) {
            throw new RuntimeException("get local address failed");
        }

        return localAddr;
    }

    public static String getLocalHostname() {
        String hostname = "";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
            if ("local".equalsIgnoreCase(hostname) || "localhost".equalsIgnoreCase(hostname)
                    || StringUtils.startsWithIgnoreCase(hostname, "127.0.0.")) {
                hostname = UUID.randomUUID().toString();
            }
        }  catch (UnknownHostException e) {
            log.warn("InetAddress.getLocalHost failed");
        }

        if (StringUtils.isEmpty(hostname)) {
            throw new RuntimeException("get hostname failed");
        }

        return hostname;
    }
}
